const app = getApp()

Page({
  data: {
    // 游戏状态
    gameStarted: false,
    gameOver: false,
    isPaused: false,
    countdown: 3,
    
    // 游戏数据
    score: 0,
    level: 1,
    combo: 0,
    
    // 当前指令
    currentInstruction: null,
    isReverse: true, // 是否为反向操作模式
    instructionColor: 'rgba(255, 255, 255, 0.1)', // 初始背景色
    
    // 倒计时进度
    timeLimit: 3000,
    timeRemaining: 3000,
    progressInterval: null,
    progressPercent: 100,
    timeRemainingText: '3.0',
    
    // 指令配置
    instructions: {
      direction: [
        { text: '左', icon: '👈', value: 'left' },
        { text: '右', icon: '👉', value: 'right' },
        { text: '上', icon: '👆', value: 'up' },
        { text: '下', icon: '👇', value: 'down' }
      ],
      action: [
        { text: '点击', icon: '👆', value: 'click' },
        { text: '摇晃', icon: '📱', value: 'shake' }
      ]
    },
    
    // 其他
    isNewRecord: false,
    gameTimer: null,
    instructionTimeout: null,
    nextInstructionTimer: null  // 新增：用于跟踪下一个指令的定时器
  },

  onLoad() {
    console.log('game onLoad');
    this.startCountdown()
  },

  onShow() {
    // 监听摇一摇
    this.enableShakeDetection()
  },

  onHide() {
    this.cleanup()
  },

  onUnload() {
    this.cleanup()
  },

  // 清理定时器
  cleanup() {
    if (this.data.gameTimer) {
      clearTimeout(this.data.gameTimer)
      this.data.gameTimer = null
    }
    if (this.data.instructionTimeout) {
      clearTimeout(this.data.instructionTimeout)
      this.data.instructionTimeout = null
    }
    if (this.data.nextInstructionTimer) {
      clearTimeout(this.data.nextInstructionTimer)
      this.data.nextInstructionTimer = null
    }
    if (this.data.progressInterval) {
      clearInterval(this.data.progressInterval)
      this.data.progressInterval = null
    }
  },

  // 启用摇一摇检测
  enableShakeDetection() {
    wx.onAccelerometerChange((res) => {
      const { x, y, z } = res
      const acceleration = Math.sqrt(x * x + y * y + z * z)
      if (acceleration > 2.5) { // 阈值可调整
        this.onShakeDetected()
      }
    })
    
    wx.startAccelerometer({
      interval: 'normal'
    })
  },

  // 摇一摇被检测到
  onShakeDetected() {
    if (this.data.currentInstruction && this.data.currentInstruction.type === 'action') {
      this.onActionClick({ currentTarget: { dataset: { action: 'shake' } } })
    }
  },

  // 开始倒计时
  startCountdown() {
    console.log('startCountdown');
    
    const countdown = () => {
      if (this.data.countdown > 1) {
        this.setData({
          countdown: this.data.countdown - 1
        })
        setTimeout(countdown, 1000)
      } else {
        this.setData({
          countdown: 0,
          gameStarted: true,
          instructionColor: this.getRandomColor() // 设置初始颜色
        }, () => {
          console.log('startCountdown 开始倒计时');
          
          this.generateNextInstruction()
        })
      }
    }
    countdown()
  },

  // 开始游戏
  startGame() {
    this.cleanup() // 确保清理所有定时器
    this.generateNextInstruction()
  },

  // 生成随机颜色
  getRandomColor() {
    const colors = [
      'rgba(255, 182, 193, 0.5)',  // 浅粉色
      'rgba(173, 216, 230, 0.5)',  // 浅蓝色
      'rgba(144, 238, 144, 0.5)',  // 浅绿色
      'rgba(255, 218, 185, 0.5)',  // 浅橙色
      'rgba(221, 160, 221, 0.5)',  // 浅紫色
      'rgba(255, 228, 196, 0.5)',  // 浅米色
      'rgba(176, 224, 230, 0.5)',  // 浅青色
      'rgba(255, 192, 203, 0.5)'   // 浅玫瑰色
    ]
    return colors[Math.floor(Math.random() * colors.length)]
  },

  // 生成下一个指令
  generateNextInstruction() {
    console.log('generateNextInstruction');
    
    if (this.data.gameOver) return

    // 清理之前的定时器
    this.cleanup()

    // 获取时间限制
    const timeLimit = this.getTimeLimit()
    console.log('设置新的时间限制:', timeLimit);

    // 根据关卡决定指令类型
    let instructionType = 'direction'
    if (this.data.level >= 6) {
      instructionType = Math.random() < 0.3 ? 'action' : 'direction'
    }

    // 随机选择指令
    const instructionPool = this.data.instructions[instructionType]
    const randomInstruction = instructionPool[Math.floor(Math.random() * instructionPool.length)]
    
    const isSpecial = Math.random() < 0.1
    
    const instruction = {
      ...randomInstruction,
      type: instructionType,
      isSpecial: isSpecial
    }

    // 生成随机颜色
    const randomColor = this.getRandomColor()

    // 先移除动画类并设置初始状态
    this.setData({
      instructionAnimation: false,
      instructionColor: randomColor,
      timeLimit: timeLimit,
      timeRemaining: timeLimit,
      progressPercent: 100,
      timeRemainingText: (timeLimit / 1000).toFixed(1)
    }, () => {
      // 在下一帧添加动画类
      this.data.nextInstructionTimer = setTimeout(() => {
        this.setData({
          currentInstruction: instruction,
          isReverse: !isSpecial,
          instructionAnimation: true
        })

        // 设置倒计时进度更新
        const updateProgress = () => {
          const now = Date.now()
          const elapsed = now - startTime
          const remaining = Math.max(0, timeLimit - elapsed)
          const percent = (remaining / timeLimit) * 100
          
          this.setData({
            timeRemaining: remaining,
            progressPercent: percent,
            timeRemainingText: (remaining / 1000).toFixed(1)
          })
          
          if (remaining <= 0) {
            clearInterval(this.data.progressInterval)
          }
        }

        const startTime = Date.now()
        updateProgress() // 立即执行一次
        this.data.progressInterval = setInterval(updateProgress, 100)
      }, 50)
    })

    // 设置指令超时
    this.data.instructionTimeout = setTimeout(() => {
      this.onTimeout()
    }, timeLimit)
  },

  // 获取时间限制（根据关卡调整）
  getTimeLimit() {
    if (this.data.level <= 5) return 3000 // 3秒
    if (this.data.level <= 10) return 2000 // 2秒
    return 1500 // 1.5秒
  },

  // 方向按钮点击
  onDirectionClick(e) {
    const direction = e.currentTarget.dataset.direction
    this.handleAnswer(direction)
  },

  // 动作按钮点击
  onActionClick(e) {
    const action = e.currentTarget.dataset.action
    this.handleAnswer(action)
  },

  // 处理答案
  handleAnswer(answer) {
    if (!this.data.currentInstruction || this.data.gameOver) return

    clearTimeout(this.data.instructionTimeout)
    clearInterval(this.data.progressInterval) // 清理进度更新定时器

    const instruction = this.data.currentInstruction
    const isCorrect = this.checkAnswer(answer, instruction)

    if (isCorrect) {
      this.onCorrectAnswer()
    } else {
      this.onWrongAnswer()
    }
  },

  // 检查答案是否正确
  checkAnswer(answer, instruction) {
    if (instruction.isSpecial) {
      // 特殊指令：正向操作
      return answer === instruction.value
    } else {
      // 普通指令：反向操作
      if (instruction.type === 'direction') {
        const opposites = {
          'left': 'right',
          'right': 'left',
          'up': 'down',
          'down': 'up'
        }
        return answer === opposites[instruction.value]
      } else {
        // 动作指令的反向操作
        const opposites = {
          'click': 'shake',
          'shake': 'click'
        }
        return answer === opposites[instruction.value]
      }
    }
  },

  // 正确答案
  onCorrectAnswer() {
    wx.vibrateShort()
    
    const newCombo = this.data.combo + 1
    const scoreIncrease = 10 + (newCombo * 2) // 连击加分
    const newScore = this.data.score + scoreIncrease

    // 检查是否升级
    const newLevel = Math.floor(newScore / 100) + 1

    this.setData({
      score: newScore,
      combo: newCombo,
      level: newLevel
    }, () => {
      // 生成下一个指令
      if (!this.data.gameOver) {  // 只有在游戏未结束时才生成下一个指令
        this.data.nextInstructionTimer = setTimeout(() => {
          console.log('generateNextInstruction 生成下一个指令');
          this.generateNextInstruction()
        }, 500)
      }
    })
  },

  // 错误答案
  onWrongAnswer() {
    this.endGame()
  },

  // 超时
  onTimeout() {
    this.endGame()
  },

  // 结束游戏
  endGame() {
    wx.vibrateLong()
    
    const bestScore = wx.getStorageSync('bestScore') || 0
    const isNewRecord = this.data.score > bestScore

    // 本地存储作为备用
    if (isNewRecord) {
      wx.setStorageSync('bestScore', this.data.score)
      app.globalData.bestScore = this.data.score
    }

    // 上传分数到云端
    this.uploadScore()

    this.setData({
      gameOver: true,
      isNewRecord: isNewRecord
    })

    this.cleanup()
  },

  // 上传分数到云端
  uploadScore() {
    const app = getApp()
    // 从本地存储获取最新的用户信息，避免使用可能过期的app.globalData
    const userInfo = wx.getStorageSync('userInfo')
    const openid = app.globalData.openid
    
    console.log('准备上传分数...')
    console.log('当前用户信息:', userInfo)
    console.log('当前openid:', openid)
    console.log('上传分数:', this.data.score)
    
    // 检查用户是否已登录
    if (!openid) {
      console.warn('⚠️ 用户可能未完成登录，openid为空')
      // 可以在这里重新触发登录
      app.getOpenId()
    }
    
    wx.cloud.callFunction({
      name: 'updateScore',
      data: {
        score: this.data.score,
        nickname: userInfo ? userInfo.nickName : '匿名玩家',
        avatarUrl: userInfo ? userInfo.avatarUrl : '',
        combo: this.data.combo,
        level: this.data.level
      },
      success: res => {
        console.log('[云函数] [updateScore] 调用成功', res)
        if (res.result.success) {
          console.log('✅ 分数上传成功！')
          if (res.result.insertId) {
            console.log('📝 新增记录ID:', res.result.insertId)
          }
          if (res.result.message) {
            console.log('📋 服务器消息:', res.result.message)
          }
          
          // 更新本地最佳分数
          app.globalData.bestScore = res.result.bestScore
          wx.setStorageSync('bestScore', res.result.bestScore)
          
          // 如果是新纪录，更新显示
          if (res.result.isNewRecord && !this.data.isNewRecord) {
            this.setData({
              isNewRecord: true
            })
          }
        } else {
          console.error('❌ 分数上传失败:', res.result.error)
          if (res.result.needLogin) {
            console.log('🔄 需要重新登录')
            // 重新获取openid
            app.getOpenId()
          }
        }
      },
      fail: err => {
        console.error('[云函数] [updateScore] 调用失败', err)
        // 云端上传失败时，使用本地存储作为备用
        wx.showToast({
          title: '网络异常，分数已本地保存',
          icon: 'none'
        })
      }
    })
  },

  // 重新开始游戏
  restartGame() {
    this.cleanup() // 确保清理所有定时器
    this.setData({
      gameStarted: false,
      gameOver: false,
      isPaused: false,
      countdown: 3,
      score: 0,
      level: 1,
      combo: 0,
      currentInstruction: null,
      isReverse: true,
      isNewRecord: false
    }, () => {
      this.startCountdown()
    })
  },

  // 分享结果
  shareResult() {
    wx.showShareMenu({
      withShareTicket: true
    })
    
    // 生成梗图文案
    const quotes = [
      `我反向操作了${this.data.combo}次，结果第${this.data.combo + 1}次系统居然玩真的？！`,
      `本以为自己很聪明，结果被"反着做"游戏玩得团团转！`,
      `分数${this.data.score}，我的大脑已经彻底混乱了...`,
      `朋友们，有谁能告诉我左右到底是哪边？`
    ]
    
    const randomQuote = quotes[Math.floor(Math.random() * quotes.length)]
    
    wx.showModal({
      title: '分享战绩',
      content: randomQuote,
      confirmText: '复制',
      success: (res) => {
        if (res.confirm) {
          wx.setClipboardData({
            data: `${randomQuote} 我在"必须反着做"游戏中得了${this.data.score}分！`,
            success: () => {
              wx.showToast({
                title: '已复制到剪贴板',
                icon: 'success'
              })
            }
          })
        }
      }
    })
  },

  // 返回首页
  goHome() {
    wx.navigateBack()
  },

  // 暂停游戏
  pauseGame() {
    this.setData({
      isPaused: true
    })
    clearTimeout(this.data.instructionTimeout)
  },

  // 继续游戏
  resumeGame() {
    this.setData({
      isPaused: false
    })
    
    // 重新设置指令超时
    const timeLimit = this.getTimeLimit()
    this.data.instructionTimeout = setTimeout(() => {
      this.onTimeout()
    }, timeLimit)
  }
}) 